<?php
namespace Assistant\Model;
use IDCU\Model\RelationModel;

class AccountModel extends RelationModel
{
    protected $excelTitle = array();

    protected $_validate = array(
        array('pay_money','/^(([1-9]\d*)|0)(\.\d{1,2})?$/','请填写正确的金额',0,'regex',3),
    );

    protected $_link = array(
            'Community' => array(
            'mapping_type' => self::BELONGS_TO,
            'class_name' => 'Community',
            'mapping_name' => 'community',
            'foreign_key' => 'community_id'
            ),
            'Zone' => array(
                'mapping_type' => self::BELONGS_TO,
                'class_name' => 'Zone',
                'mapping_name' => 'zone',
                'foreign_key' => 'zone_id'
            ),
            'Building' => array(
                'mapping_type' => self::BELONGS_TO,
                'class_name' => 'Building',
                'mapping_name' => 'building',
                'foreign_key' => 'building_id'
            ),
            'Unit' => array(
                'mapping_type' => self::BELONGS_TO,
                'class_name' => 'Unit',
                'mapping_name' => 'unit',
                'foreign_key' => 'unit_id'
            ),

            'Room' => array(
                'mapping_type' => self::BELONGS_TO,
                'class_name' => 'Room',
                'mapping_name' => 'room',
                'foreign_key' => 'room_id'
            ),

            'Log' => array(
                'mapping_type' => self::HAS_MANY,
                'class_name' => 'AccountLog',
                'mapping_name' => 'log',
                'foreign_key' => 'account_id'
            )
       );
    public function createAccount($arr, $roomId){
        $total = 0;
        foreach ($arr as $v){
            $exData = M('Expense')->find($v);
            $total += $exData['money'];
            M('Expense')->data(array('is_edit'=>0, 'id'=>$v))->save();
        }
        $expenseId = implode(',', $arr);
        $data['expense_id'] = $expenseId;
        $data['total_money'] = $total;
        $data['create_time'] = time();
        $data['room_id'] = $roomId;
//        var_dump($data);die;
        $id = $this->add($data);
        if($id) {
            $is_ok = $this->postAccount($id);
            if(!$is_ok['error']==0){
                $sign['status'] = 1;
                $sign['id'] = $id;
                return $sign;
            }else{
                $sign['status'] = 0;
                $sign['error'] = $is_ok['info'];
            }
            $sign['status'] = 1;
            $sign['id'] = $id;
            return $sign;
        }
        $sign['status'] = 0;
        $sign['error'] = $this->getError();
        return $sign;
    }

    public function excelDtail($id){

        $expense_id = $this->find($id)['expense_id'];
        $expense_id = explode(',', $expense_id);
        foreach ($expense_id as $v) {
            $expenseData[] = M('Expense')->where(array('id'=>$v))->find();
        }
        $data = array();
        foreach ($expenseData as $k=>$v) {
            $data [$k]['type'] = D('Admin/Dict')->getTitle('expenseType',$v['type']);
            $data [$k]['money'] = $v['money'];
        }
        return $data;
    }


    public function checkUnique($roomId){
        $data = $this->where(array(
            'room_id'=>$roomId,
            'status'=>0))->find();
        return $data['id'];
    }

    public function postAccount($account_id)
    {
        $_data = $this->find($account_id);
        $expense_id = explode(',', $_data['expense_id']);
        $data = array();
        foreach ($expense_id as $k=>$v){
            $expenseData = M('Expense')->find($v);
            $data['detail'][$k]['title'] =  getDicName('expenseType', $expenseData['type']);
            $data['detail'][$k]['money'] =  $expenseData['money'];
            $data['detail'][$k]['year'] =  $expenseData['year'];
            $data['detail'][$k]['status'] =  $expenseData['status'];
        }
        $data['id'] = $_data['id'];
        $data['room_id'] = $_data['room_id'];
        $data['room_name'] = $_data['room_name'];
        $data['totalfee'] = $_data['total_money'];
        $data['paidfee'] = $_data['pay_money'];
        $data['status'] = $_data['status'];
        $data['create_time'] = $_data['create_time'];
        $data['detail'] = json_encode($data['detail']);
//        echo '<pre>';
//        var_dump($data);die;
        $url = 'http://smart.wx91go.com/index.php?g=Home&m=Index&a=HouseCharge&token=ofanap1448334221';
        apiPost($url, $data);
    }

    public function postPay($log_id){
        $logData = M('AccountLog')->find($log_id);
        $data['id'] = $logData['account_id'];
        $data['paidfee'] = $logData['pay_money'];
        $data['payer'] = $logData['payer_name'];
        $data['paytime'] = $logData['pay_time'];
        $data['payway'] = getDicName('payWay', $logData['pay_way']);
        $url = 'http://smart.wx91go.com/index.php?g=Home&m=Index&a=PaidHouseCharge&token=ofanap1448334221';
        apiPost($url, $data);
    }

    public function accountSearch($pageSize = 10) {
        $uid = session('authId');
        $community_id = I('community_id');
        if(!$community_id)
            $community_id = getCommunityId($uid);
        if(!$community_id)
            return false;
         $zone_id = I('param.zone_id');
         $building_id = I('param.building_id');
         $unit_id = I('param.unit_id');
         $room_id = I('param.room_id');
         $year = I('param.year');
         $status = I('param.status');
         $key = I('param.key');
         $where = array();
         if($key){
            if(preg_match("/^\d+$/", $key))
                 $where['payer_phone'] = array('like',"%$key%");
             else
                 $where['payer_name'] = array('like',"%$key%");
         }
         if($community_id)
             $where['community_id'] = array('in',$community_id);
         if($zone_id)
             $where['zone_id'] = $zone_id;
         if($building_id)
             $where['building_id'] = $building_id;
         if($unit_id)
             $where['unit_id'] = $unit_id;
         if($room_id)
             $where['room_id'] = $room_id;
         if($year)
             $where['year'] = $year;
         if(is_numeric($status))
             $where['status'] = $status;
         /************************************* 翻页 ****************************************/
         $count = $this->where($where)->count();
         $page = new \ZL\Page($count, $pageSize);
         $data['page'] = $page->show();
         /************************************** 取数据 ******************************************/
         $accountData = $this->relation(true)->where($where)->limit($page->limit.','.$page->listRows)->select();
        foreach ($accountData as &$v) {
            if($v['status']==1)
                $v['look'] = 1;
            else {
                $dd = M('Wyf_visits', 'tp_', 'DB_WX')->where(array('wid' => $v['id']))->find();
                if ($dd)
                    $v['look'] = 1;
            }
        }
         $data['data'] = $accountData;
         return $data;
    }

    public function detail(){
        $expense_id = I('expense_id');
        $room_id = I('room_id');
        if ($expense_id && $room_id) {
            $accData = $this->relation(true)->where(array(
                'expense_id' => array('like', $expense_id),
                'room_id' => array('eq', $room_id)
            ))->find();
        } else {
            $id = I('param.id');
            $accData = $this->relation(true)->find($id);
        }
        $expense_id = explode(',', $accData['expense_id']);
        foreach($expense_id as $v){
            $accData['data'][] = M('Expense')->find($v);
        }
        return $accData;
    }

    public function pay($toPost=true){
        $id = I('param.id');
        $pay_money = I('pay_money');
        $is_ok = $this->checkMoney($id, $pay_money, $toPost);
        if($is_ok){
            $_data['pay_money'] = $is_ok['pay_money'];
            if($is_ok['other_money']==0)
                $_data['status'] = 1;
            $ss = $this->data($_data)->where(array('id'=>$id))->save();
            if($ss){
                $is_log = $this->createLog();
                if($toPost)
                    $this->postPay($is_log);
                $data = array();
                $data['status'] = 1;
                return $data;
            }
        }
        return false;
    }

    public function checkMoney($account_id,$pay_money, $toPost)
    {
        $data = $this->find($account_id);
        $pay_money = $data['pay_money']+$pay_money;
        $other_money = $data['total_money'] - $pay_money;
        if($other_money >= 0){
            if($other_money == 0)
                $this->expenseStatus($account_id, $toPost);
            $_data['status'] = 1;
            $_data['pay_money'] =$pay_money;
            $_data['other_money'] =$other_money;
            return $_data;
        }
        return false;
    }

    public function expenseStatus($account_id, $toPost){
        $accountData = $this->find($account_id);
        $expenseData = explode(',', $accountData['expense_id']);
        foreach ($expenseData as $v){
            M('Expense')->data(array('status'=>1,'is_edit'=>0,'id'=>$v,'pay_way' => I('pay_way')?I('pay_way'):2,'pay_time'=>time()))->save();
        }
    }

    public function createLog(){
        $data['account_id'] = I('id');
        $data['pay_way'] = I('pay_way')?I('pay_way'):2;
        $data['payer_name'] = I('payer_name');
        $data['pay_money'] = I('pay_money');
        $data['remark'] = I('remark');
        $time = I('pay_time');
        if(is_numeric($time))
            $data['pay_time'] = $time;
        else
            $data['pay_time'] = strtotime(I('pay_time'));
        $id = M('AccountLog')->data($data)->add();
        if($id)
            return $id;
        return false;
    }

    public function searchLog($pageSize=20,$limit=false){
        $key = I('param.key');
        $where = array();
        $start_time = I('start_time');
        $end_time = I('end_time');
        $payWay = I('payWay');
        if($limit){
            $community_id = getCommunityData(1);
            $where['c.community_id'] = array('in',$community_id);
        }
        if ($start_time)
            $start_time = strtotime($start_time);
        if ($end_time)
            $end_time = strtotime($end_time)-1;
        if ($start_time && !$end_time)
            $where['a.pay_time'] = array('egt',$start_time);
        elseif (!$start_time && $end_time)
            $where['a.pay_time'] = array('elt',$end_time);
        elseif ($start_time && $end_time)
            $where['a.pay_time'] = array('BETWEEN',"$start_time,$end_time");
//        if ($status)
//            $where['isuse'] = array('in','%'.$status.'%');
        if($key){
            if(preg_match("/^\d+$/", $key))
                $map['c.householder_mobi'] = array('like',"%$key%");
            else{
                $map['a.payer_name'] = array('like',"%$key%");
                $map['c.name'] = array('like',"%$key%");
                $map['c.householder_name'] = array('like',"%$key%");
            }
            $map['_logic'] = 'or';
            $where['_complex'] = $map;
        }
        if($where){

        }
        if($payWay){
            $where['a.pay_way'] =$payWay;
        }
        $where['b.id'] = array('gt',0);
        /************************************* 翻页 ****************************************/
        $modle = M('AccountLog');
        $count = $modle->alias('a')->join("left join zh_account b on a.account_id=b.id left join zh_room c on b.room_id=c.id")->where($where)->count();
        $page = new \ZL\Page($count, $pageSize, C('PAGE_01'));
        $data['page'] = $page->show();
        /************************************** 取数据 ******************************************/
        $logData = $modle->alias('a')->field('a.*, b.no, c.name, c.full_parent_name, c.householder_name, c.householder_mobi as tel')->join("left join zh_account b on a.account_id=b.id left join zh_room c on b.room_id=c.id")->where($where)->order('a.id desc')->limit($page->limit.','.$page->listRows)->select();
        $data['data'] = $logData;
//        var_dump($where);
//        myDump($logData);die;
        return $data;
    }

    public function dumpExcel(){
        $_data = D('Admin/Finance')->ExpenseOrder(9999,1);
        $payWay = D('Admin/Dict')->getDict('payWay');
            foreach ($_data['data'] as $k => $v) {
                $data[$k]['no'] = '编号'.$v['no'];
                $data[$k]['pay_time'] = date('Y-m-d', $v['pay_time']);
                $data[$k]['payer_name'] = $v['payer_name'];
                $data[$k]['householder_name'] = $v['householder_name'];
                $data[$k]['tel'] = $v['tel'];
                $data[$k]['pay_way'] = $v['pay_way'];
                $data[$k]['pay_money'] = $v['pay_money'];
                $data[$k]['room_name'] = $v['room_name'];
    //                    myDump($v['accountDetail']);die;
                foreach ($v['accountDetail'] as $kk =>&$vv) {
                    if (!$this->excelTitle['th'][$vv['type']] && $vv['type']) {
                        $vv['sort'] = $this->excelTitle['th'][$vv['type']] = $this->excelTitle['num']?$this->excelTitle['num']:1;
                        $this->excelTitle['num'] || $this->excelTitle['num']=1;
                        $this->excelTitle['num']++;
                    } else {
                        $vv['sort'] == $this->excelTitle['th'][$vv['type']];
                    }
                    if($data[$k]['accountDetail'][$vv['type']])
                        $data[$k]['accountDetail'][$vv['type']] .= ','.$vv['money'];
                    else
                        $data[$k]['accountDetail'][$vv['type']] = $vv['money'];
                }
            }
            foreach ($data as $k => &$v) {
                foreach ($this->excelTitle['th'] as $kk=>&$vv){
                    $has = false;
                    foreach ($v['accountDetail'] as $kkk=>$vvv) {
                        if($kkk==$kk) {
                            if($v[$kk]){
                                $v[$kk] .= ','.$vvv;
                            }else {
                                $v[$kk] = $vvv;
                            }
                            $has = 1;
                        }
                    }
                    if(!$has)
                        $v[] = '';
                }
                unset($data[$k]['accountDetail']);
            }
            $title = array('账单号','支付时间','缴费人姓名','户主姓名','户主联系方式','支付方式','金额','房间地址');
            foreach ($this->excelTitle['th'] as $k=>$v) {
                $title[] = $k;
            }

//                dd($this->excelTitle);
        //        myDump($data);die;
        dumpExcel($title, $data,'费用账单');
    }


    public function getNo($room_id) {
        $no = $this->where(array('room_id'=>$room_id))->order('no desc')->find();
        if($no){
            $str = $no['no'];
            $str1 = substr($str,-4);
            $str1 = (int)$str1;
            $str1 = $str1+1;
            $str2 = substr($str,0,-4);
            return $str2.sprintf('%04s', $str1);
        }
        $data = M('Room')->where(array('id'=>$room_id))->find();
        return $data['no'].'0001';
    }
    
    public function _before_write(&$data)
    {
        parent::_before_write($data); // TODO: Change the autogenerated stub
////        if($data['start_time'] && strpos($data['start_time'],'/'))
//            $data['start_time'] = strtotime($data['start_time']);
////        if($data['end_time'] && strpos($data['end_time'],'/'))
//            $data['end_time'] = strtotime($data['end_time']);
////        if($data['close_time'] && strpos($data['close_time'],'/'))
//            $data['close_time'] = strtotime($data['close_time']);

        if($data['room_id']){
            $room = D('Admin/Room')->where(array('id'=>$data['room_id']))->find();
            $data['room_name'] = $room['full_parent_name'].$room['name'];
            $data['community_id'] = $room['community_id'];
            $data['zone_id'] = $room['zone_id'];
            $data['building_id'] = $room['building_id'];
            $data['unit_id'] = $room['unit_id'];
            if(!$data['no'])
                $data['no'] = $this->getNo($data['room_id']);
        }
    }

    public function _after_insert($data, $options)
    {
        parent::_after_insert($data, $options); // TODO: Change the autogenerated stub
    }

    public function _after_delete($data, $options)
    {
        parent::_after_delete($data, $options); // TODO: Change the autogenerated stub
    }
}